import pickle
import os
import numpy as np
import tensorflow.keras.backend as K
from tensorflow.keras.utils import to_categorical
type = 'coarse'#coarse|fine
def precision(y_true, y_pred):
    TP = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))#TP
    N = (-1)*K.sum(K.round(K.clip(y_true-K.ones_like(y_true), -1, 0)))#N
    TN=K.sum(K.round(K.clip((y_true-K.ones_like(y_true))*(y_pred-K.ones_like(y_pred)), 0, 1)))#TN
    FP=N-TN
    precision = TP / (TP + FP + K.epsilon())#TT/P
    return precision

def recall(y_true, y_pred):
    TP = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))#TP
    P=K.sum(K.round(K.clip(y_true, 0, 1)))
    FN = P-TP #FN=P-TP
    recall = TP / (TP + FN + K.epsilon())#TP/(TP+FN)
    return recall
def load_pickle(filename):
    filename = os.path.join('cifar-100-python', filename)
    with open(filename, 'rb') as fo:
        data = pickle.load(fo, encoding='latin1')
    return data

def load_CIFAR_batch(filename):
    data = load_pickle(filename)
    X = data['data']        # X, ndarray, 像素值
    Y = data[type+'_labels']      # Y, list, 标签, 分类

    # reshape, 一维数组转为矩阵10000行3列。每个entries是32x32
    # transpose，转置
    # astype，复制，同时指定类型
    X = X.reshape(-1, 3, 32, 32).transpose(0,2,3,1).astype("float")/255.
    Y = np.array(Y)
    return X, Y
def load_data():
    # 训练集
    x_train,y_train = load_CIFAR_batch('train') # [ndarray, ndarray] 合并为一个ndarray

    # 测试集
    x_test,y_test = load_CIFAR_batch('test')

    #label_names
    label_names = load_pickle('meta')[type+'_label_names']
    # y_train = tf.one_hot(y_train,len(label_names)) #独热编码
    # y_test  = tf.one_hot(y_test,len(label_names))
    y_train = to_categorical(y_train,len(label_names))#独热编码
    y_test = to_categorical(y_test,len(label_names))#独热编码
    return x_train,y_train,x_test,y_test,label_names